import React, { useEffect, useState } from 'react';
import { getStockInOutCountByWarehouse } from '@/services/echart/api';
import { Pie } from "@ant-design/charts";
import {Card} from "antd";
import {type ProColumns, ProTable} from "@ant-design/pro-components";

const PlotMaps = {};

const StockInOutChart: React.FC = () => {
  const [stockInData, setStockInData] = useState<API.StockInSummaryByWarehouse[]>([]);
  const [stockOutData, setStockOutData] = useState<API.StockInOutSummaryByWarehouse[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await getStockInOutCountByWarehouse();
        setStockInData(response.data.stockInData);
        setStockOutData(response.data.stockOutData);
      } catch (error) {
        console.error('获取出入库数据失败:', error);
      }
    };

    fetchData();
  }, []);

  const showTooltip = (evt, pie) => {
    Object.keys(PlotMaps).forEach((plot) => {
      if (plot !== pie) {
        PlotMaps[plot].chart.emit('tooltip:show', {
          data: { data: { warehouseCode: evt.data.data.warehouseCode } },
        });
        PlotMaps[plot].chart.emit('element:highlight', {
          data: { data: { warehouseCode: evt.data.data.warehouseCode } },
        });
      }
    });
  };

  const hideTooltip = (evt, pie) => {
    Object.keys(PlotMaps).forEach((plot) => {
      if (plot !== pie) {
        PlotMaps[plot].chart.emit('tooltip:hide', {
          data: { data: { warehouseCode: evt.data.data.warehouseCode } },
        });
        PlotMaps[plot].chart.emit('element:unhighlight', {
          data: { data: { warehouseCode: evt.data.data.warehouseCode } },
        });
      }
    });
  };

  const stockInConfig = {
    angleField: 'stockInCount',
    colorField: 'warehouseCode',
    data: stockInData,
    label: {
      text: 'stockInCount',
    },
    legend: false,
    tooltip: {
      title: 'warehouseName',
    },
    interaction: {
      elementHighlight: true,
    },
    state: {
      inactive: { opacity: 0.5 },
    },
  };
  const stockOutConfig = {
    angleField: 'stockOutCount',
    colorField: 'warehouseCode',
    data: stockOutData,
    label: {
      text: 'stockOutCount',
    },
    legend: false,
    tooltip: {
      title: 'warehouseCode',
    },
    interaction: {
      elementHighlight: true,
    },
    state: {
      inactive: { opacity: 0.5 },
    },
  };

  const stockInColumns: ProColumns<API.StockInSummaryByWarehouse>[] = [
    {
      title: '仓库名',
      hideInSearch: true,
      width: 120,
      editable: false,
      dataIndex: 'warehouseName',
    },
    {
      title: '出库频次',
      hideInSearch: true,
      width: 120,
      editable: false,
      dataIndex: 'stockInCount',
    },
  ];
  const stockOutColumns: ProColumns<API.StockOutSummaryByWarehouse>[] = [
    {
      title: '仓库名',
      hideInSearch: true,
      width: 120,
      editable: false,
      dataIndex: 'warehouseName',
    },
    {
      title: '出库频次',
      hideInSearch: true,
      width: 120,
      editable: false,
      dataIndex: 'stockOutCount',
    },
  ];
  return (<Card>
      <div style={{ display: 'flex', justifyContent: 'space-around' }}>
        <Card>
          <div>
            <h2>入库频次（仓库维度）</h2>
            <Pie
              style={{ width: '50%' }}
              {...stockInConfig}
              onReady={(plot) => {
                PlotMaps.stockInPie = plot;
                plot.chart.on('interval:pointerover', (evt) => {
                  showTooltip(evt, 'stockInPie');
                });
                plot.chart.on('interval:pointerout', (evt) => {
                  hideTooltip(evt, 'stockInPie');
                });
              }}
            />
          </div>
          <ProTable<API.StockInSummaryByWarehouse>
            columns={stockInColumns}
            cardBordered
            dataSource={stockInData}
            searchFormRender={() => <></>}
            options={{
              setting: {
                listsHeight: 400,
              },
            }}
            headerTitle="入库频次"
          />
        </Card>
        <Card>
          <div>
            <h2>出库频次（仓库维度）</h2>
            <Pie
              style={{ width: '50%' }}
              {...stockOutConfig}
              onReady={(plot) => {
                PlotMaps.stockOutPie = plot;
                plot.chart.on('interval:pointerover', (evt) => {
                  showTooltip(evt, 'stockOutPie');
                });
                plot.chart.on('interval:pointerout', (evt) => {
                  hideTooltip(evt, 'stockOutPie');
                });
              }}
            />
          </div>
          <ProTable<API.StockOutSummaryByWarehouse>
            columns={stockOutColumns}
            cardBordered
            dataSource={stockOutData}
            searchFormRender={() => <></>}
            options={{
              setting: {
                listsHeight: 400,
              },
            }}
            headerTitle="出库频次"
          />
        </Card>

      </div>
    </Card>
  );
};

export default StockInOutChart;
